package net.zjitc.logincheckcode.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author Administrator
 * @Date 2020/6/4 15:48
 **/
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.创建一图片对象 BufferedImage
        * 2.使用画笔Graphics
        * 1)填充背景颜色
        * 2）画边框
        * 3）写字符（随机产生）
        * 4）画干扰线
        * 3.将图片输出到页面显示ImageIO*/
        /*图片的宽高*/
        int width=80;
        int height=30;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        /*2.使用画笔功能美化图片*/
        Graphics g=image.getGraphics();
        /*设置画笔颜色*/
        g.setColor(Color.GRAY);
        /*填充背景颜色*/
        g.fillRect(0,0,width,height);
        /*画边框*/
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);
        /*产生4个随机字符*/
        String s="qwertyuiopasdfghjklzxcvbnmQWRTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random=new Random();
        /*sb用于存储产生的4个随机字符*/
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < 4; i++) {
            /*产生随机索引*/
            int index =random.nextInt(s.length());
            /*根据索引得到随机字符*/
            char ch = s.charAt(index);
            /*保存随机字符*/
            sb.append(ch);
        }
        /*验证码字符串保存在session域对象*/
        req.getSession().setAttribute("session_code",sb.toString());
        /*写随机字符*/
        g.setColor(Color.YELLOW);
        /*设置字体*/
        g.setFont(new Font("黑体",Font.BOLD,22));
        g.drawString(sb.toString(),20,20);
        /*3.将图片输出到页面显示*/
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
